import { computed, onMounted, onUnmounted, ref } from "vue";
import { useStore } from "vuex";
import { GlobalDataProps } from "@/store";
import { Modal } from "ant-design-vue";
import useSaveWork from "./useSaveWork";
import {
  useRoute,
  RouterView,
  RouterLink,
  onBeforeRouteLeave,
} from "vue-router";
import { takeScreenshotAndUpload } from "@/helper";

function usePublishWork(){
    const { saveWork } = useSaveWork();
    const route = useRoute();
    const currentWorkId = route.params.id;

    const store = useStore<GlobalDataProps>();
    const channels = computed(() => store.state.editor.channels);
    const isPublishing = ref(false);

    const publishWork = async (el: HTMLElement) => {
        try {
          //1. 截图上传
          const resp = await takeScreenshotAndUpload(el)
          if (resp) {
            // 2. 更新图片的coverimg
            console.log(resp.data.urls);
            // store.commit("updatePage", { key: "coverImg", value: resp.data.urls[0], isRoot: true });
            // 3. 保存work
            await saveWork();
            // 4. 发布
            // await store.dispatch("publishWork", { urlParams: { id: currentWorkId }});
            // 5. 创建channel
            await store.dispatch('fetchChannels', {urlParams: {id: currentWorkId}});
            console.log('publishWork after fetchChannels',channels.value);
            if (channels.value?.length === 0){
              await store.dispatch('createChannel', {data: {
                name: '默认',
                workId: parseInt(currentWorkId as string),
              }});
            }
          }
        } catch (e) {
          console.error(e);
        } finally {
          isPublishing.value = false;
        }
      };

      return {
        publishWork,
        isPublishing,
      }
}

export default usePublishWork;